<?php
/**
 * 管理员基础类
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/21
 * Time: 17:25
 */
namespace app\common\controller;
use think\Db;
class UserCm{

    /**
     * 查询字段
     * @param string $username  用户名
     * @param string $field   查询字段
     * @return mixed
     */
    public function GetField($username, $field){
        $cdn['username'] = $username;
        $field_value = Db::name('user')->where($cdn)->value($field);
        return $field_value;
    }

    /**
     * 登陆，密码校验
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|string 返回sid  或 false
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function Login($username, $password){
        $password_db = $this->GetField($username, 'password');
        if($password != $password_db){
            return false;
        }
        $crt_time = CommonFun::GetTime();
        $sid = CommonFun::GetRandomString(32, 1);
        $data = ['sid'=>$sid,'login_time'=>$crt_time, 'online_time'=>$crt_time];
        $cdn['username'] = $username;
        Db::name('manager')->where($cdn)->update($data);
        return $sid;
    }

    /**
     * 注销
     * @param string $username 用户名
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function Logout($username)
    {
        $sid = 'logout';
        $cdn['username'] = $username;
        $data = ['sid'=>$sid];
        $result = Db::name('user')->where($cdn)->update($data);
        if($result){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 修改密码
     * @param $username
     * @param $old_pwd
     * @param $new_pwd
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @author LeeBW
     * @date 2020-12-29 19:46
     */
    public function ChangePassword($username, $old_pwd, $new_pwd)
    {
        $old_pwd_db = $this->GetField($username, 'password');
        if($old_pwd == $old_pwd_db){
            Db::name('user')->where('username', $username)->update(['password'=>$new_pwd]);
            return true;
        }
        return false;
    }
}